package cn.dakaqi.open.pingan2;

import cn.dakaqi.entities.Customer;
import cn.dakaqi.entities.Group;
import cn.dakaqi.entities.PinganOpen;
import cn.dakaqi.entities.PinganVoucherCenter;
import cn.dakaqi.entities.user.User;
import cn.dakaqi.entities.user.Volunteer;
import cn.dakaqi.pingan.entities.ActivateResult;
import cn.dakaqi.pingan.entities.InAccount;
import cn.dakaqi.pingan.util.PingAnUtil;
import cn.dakaqi.services.*;
import cn.dakaqi.services.user.UserService;
import cn.dakaqi.services.user.VolunteerService;
import cn.dakaqi.util.ConfigUtil;
import cn.dakaqi.utils.DateUtil;
import cn.dakaqi.utils.JsonResult;
import cn.dakaqi.utils.redis.RedisClientTemplate;
import cn.dakaqi.utils.sms.rongcloud.RongCloudSMS;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

/**
 * Copyright: Copyright (c)2016
 * Company: 志愿者打卡器(www.dakaqi.cn)
 * 类名称: PA2Controller <br>
 * 类描述: 先设置平安理赔卡 后购买保险
 *
 * @author: ChunYang.Zhang
 * @since: 2016/8/11 18:18
 * @version: 1.0.0
 */
@Controller
@RequestMapping(value = "/pa2")
@Slf4j
public class PA2Controller
{
    @Autowired
    UserService userService;
    @Autowired
    VolunteerService volunteerService;
    @Autowired
    GroupVolunteerService groupVolunteerService;
    @Autowired
    GroupService groupService;
    @Autowired
    PingAnUtil pingAnUtil;
    @Resource
    private PinganOpenService pinganOpenService;
    @Autowired
    private PinganVoucherCenterService pinganVoucherCenterService;
    @Autowired
    private RedisClientTemplate redisClientTemplate;
    @Autowired
    CustomerService customerService;
    @Autowired
    ConfigUtil configUtil;

    //String callBackPath = "http://test.dakaqi.cn:3030/up/pa2/finish?param=";
    /**
     * 填写购买者的信息
     *
     * @param customerCode
     * @param callBack
     * @return
     */
    @RequestMapping(method = RequestMethod.GET)
    public ModelAndView toRegPage(@RequestParam(value = "customerCode", required = true) String customerCode, @RequestParam(value = "callBack", defaultValue = "", required = false) String callBack)
    {

        if(StringUtils.isBlank(customerCode))
        {
            String view = "pingan2/message";
            ModelAndView modelAndView = new ModelAndView(view);
            modelAndView.addObject("callBack", callBack);
            modelAndView.addObject("customerCode", customerCode);
            modelAndView.addObject("message", "未授权,不可以操作");
            return modelAndView;
        }
        Customer customer = customerService.findByCode(customerCode);
        if(null == customer)
        {
            String view = "pingan2/message";
            ModelAndView modelAndView = new ModelAndView(view);
            modelAndView.addObject("callBack", callBack);
            modelAndView.addObject("customerCode", customerCode);
            modelAndView.addObject("message", "授权无效,不可以操作");
            return modelAndView;
        }

        String view = "pingan2/reg";
        ModelAndView modelAndView = new ModelAndView(view);
        modelAndView.addObject("callBack", callBack);
        modelAndView.addObject("customerCode", customerCode);
        return modelAndView;
    }

    @RequestMapping(value = "/sendCode", method = RequestMethod.POST)
    public ResponseEntity<JsonResult> sendCode(@RequestParam(value = "mobile", required = true) String mobile)
    {
        JsonResult jsonResult = new JsonResult();
        this.userService.sendVerifierCode(mobile.trim());
        jsonResult.setCode(JsonResult.CODE_SUCCESS);
        jsonResult.setMessage("验证码已发送,请注意查收!");
        return new ResponseEntity<JsonResult>(jsonResult, HttpStatus.OK);
    }

    /**
     * 购买保险
     *
     * @param customerCode
     * @param callBack
     * @param name
     * @param idCard
     * @param mobile
     * @param code
     * @param response
     * @return
     */
    @RequestMapping(value = "/create", method = RequestMethod.POST)
    public String create(@RequestParam(value = "customerCode", required = true) String customerCode,
                               @RequestParam(value = "callBack", defaultValue = "", required = false) String callBack,
                               @RequestParam("name") String name,
                               @RequestParam("idCard") String idCard,
                               @RequestParam("mobile") String mobile,
                               @RequestParam("code") String code,
                               Model model,
                               HttpServletResponse response)
    {
        log.info(customerCode + "," + callBack + "," + name + "," + idCard + "," + mobile + "," + code);
        if(StringUtils.isBlank(customerCode))
        {
            model.addAttribute("callBack", callBack);
            model.addAttribute("customerCode", customerCode);
            model.addAttribute("message", "未授权,不可以操作");
            return "pingan2/message";
        }
        Customer customer = customerService.findByCode(customerCode);
        if(null == customer)
        {
            model.addAttribute("callBack", callBack);
            model.addAttribute("customerCode", customerCode);
            model.addAttribute("message", "授权无效,不可以操作");
            return "pingan2/message";
        }
        //检查参数
        String message = checkParam(customerCode, callBack, name, idCard, mobile, code);
        if (null != message)
        {
            model.addAttribute("callBack", callBack);
            model.addAttribute("customerCode", customerCode);
            model.addAttribute("message", message);
            return "pingan2/message";
        }

        //验证码是否正确
        if (!checkVerifierCode(mobile.trim(), code))
        {
            model.addAttribute("callBack", callBack);
            model.addAttribute("customerCode", customerCode);
            model.addAttribute("message", "验证码不正确");
            return "pingan2/message";
        }

        //检查当前用户的年龄
        try
        {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            int age = DateUtil.getAgeByBirthday(sdf.parse(DateUtil.getBirthFromCardNO(idCard)));
            //若是小7大于70岁的转入无法领取页面
            if (age < 7 || age > 70)
            {
                model.addAttribute("callBack", callBack);
                model.addAttribute("customerCode", customerCode);
                model.addAttribute("message", "您的年龄不满足条件");
                return "pingan2/message";
            }
        } catch (ParseException e)
        {
            e.printStackTrace();
            model.addAttribute("callBack", callBack);
            model.addAttribute("customerCode", customerCode);
            model.addAttribute("message", "您的年龄不满足领取条件");
            return "pingan2/message";
        }
        //检查当前用户是否已开过户
        PinganOpen pinganOpen = pinganOpenService.findByIdCard(idCard);
        if (null == pinganOpen)
            pinganOpen = pinganOpenService.findByGuardianIDCard(idCard);

        if (null != pinganOpen)
        {
            PinganVoucherCenter pinganVoucherCenter = pinganVoucherCenterService.findByCardNum(pinganOpen.getCardNum());
            if(null != pinganVoucherCenter)
            {
                model.addAttribute("callBack", callBack);
                model.addAttribute("customerCode", customerCode);
                model.addAttribute("message", "数据已存在,不可以重复操作");
                return "pingan2/message";
            }
        }

        //检查当前手机用户是否已存在
        User user = this.userService.findByMobile(mobile);
        Volunteer volunteer = null;
        if(null != user)
        {
            //检查当前手机用户是否已有志愿者一号通
            volunteer = this.volunteerService.findByUserId(user.getId());
        }

        //新线程注册用户并加入一个默认的社团，获取志愿者一号通
        Group group = groupService.findByGroupCode(customer.getGroupCode());
        RegUserThread userThread = new RegUserThread(userService, volunteerService, groupVolunteerService, name, idCard, mobile, group,volunteer);
        Thread thread = new Thread(userThread);
        thread.start();


        //去橙子银行注册账号
        try
        {

            String platform = "A";
            //构造临时的会员CODE和志愿者一号通 //这个志愿者一号通是自己临时构造的，格式为：T-client-32030519810302243X
            String memberCode = "T-" + customerCode+"-" + idCard;

            PinganOpen record = pingAnUtil.regAccount(customerCode,memberCode, platform, memberCode, name, idCard, mobile, null, null, null);

            if (null != record)
            {
                String callBackPath = ConfigUtil.getAppRoot() + "pa2/finish?param=";
                callBackPath = callBackPath + callBack + ";" +customerCode + ";";
                ActivateResult activateResult = pingAnUtil.activateCard(platform, memberCode, record.getCardNum(),callBackPath);

                if (null != activateResult && "00".equals(activateResult.getState()) && StringUtils.isNotBlank(activateResult.getReturnUrl()))
                {
                    log.info("统计信息---用户跳转至平安创建用户、绑卡页面流程--->[ " + activateResult.getReturnUrl() + " ]");
                    //response.sendRedirect(activateResult.getReturnUrl());
                    return "redirect:"+activateResult.getReturnUrl();
                } else
                {
                    model.addAttribute("callBack", callBack);
                    model.addAttribute("customerCode", customerCode);
                    model.addAttribute("message", "操作失败");
                    return "pingan2/message";
                }
            }
        } catch (Exception e)
        {
            e.printStackTrace();
            model.addAttribute("callBack", callBack);
            model.addAttribute("customerCode", customerCode);
            model.addAttribute("message", e.getMessage());
            return "pingan2/message";
        }

        return null;
    }

    @RequestMapping(value = "/finish", method = RequestMethod.GET)
    public String finish(@RequestParam(value = "param", required = true) String param,Model model)
    {
        log.info("pingan2/finish----------->" + param);
        //参加格式说明： 第三方URL;第三方CUSTOMERCODE;志愿者一号通;橙子银行卡号
        String view = "pingan2/finish";
        String[] params = param.split(";");
        //这个志愿者一号通是自己临时构造的，格式为：T-client-32030519810302243X
        String callBackUrl = params[0];
        String customerCode = params[1];
        String volunteerCode = params[2];
        String cardNum = params[3];

        PinganOpen pinganOpen = this.pinganOpenService.findByCardNum(cardNum);
        model.addAttribute("pinganOpen", pinganOpen);

        //进行支持中心
        if(null == this.pinganVoucherCenterService.findByCardNum(cardNum))
        {
            PinganVoucherCenter pinganVoucherCenter = new PinganVoucherCenter(pinganOpen.getName(),cardNum,customerCode);
            pinganVoucherCenter.setCreateTime(DateUtil.getToday());
            pinganVoucherCenter.setMoney(0F);
            this.pinganVoucherCenterService.save(pinganVoucherCenter);
        }

        if(null != callBackUrl && !"null".equals(callBackUrl) && StringUtils.isNotBlank(callBackUrl))
        {
            if(callBackUrl.contains("http://"))
                return "redirect:" + callBackUrl;
            else
                return "redirect:http://" + callBackUrl;
        }



        //呼叫脉保进行购买保险，如果可以购买保险则进行购买


//        Volunteer volunteer = this.volunteerService.findByCardNO(tCode[2]);
//        VolunteerInsurance insurance = this.volunteerInsuranceService.findByVolunteerCode(volunteer.getVolunteerCode());
//
//        modelAndView.addObject("volunteer", volunteer);
//        modelAndView.addObject("insurance", insurance);
//        modelAndView.addObject("cardNum", cardNum);
//        modelAndView.addObject("backUrl", backUrl);
        return view;

    }

    @RequestMapping(value = "/yoyoPay", method = RequestMethod.GET)
    public ResponseEntity<JsonResult> yoyoPay(@RequestParam("customer") String customer,@RequestParam("type") String type)
    {
        JsonResult jsonResult = new JsonResult();
        Page<PinganVoucherCenter> data = this.pinganVoucherCenterService.findByMoney(customer,0F,1);
        if(null != data && null != data.getContent() && data.getContent().size()>0)
        {
            List<InAccount> inAccounts = new ArrayList<InAccount>();
            for(PinganVoucherCenter pvc:data.getContent())
            {
                PinganOpen pinganOpen = this.pinganOpenService.findByCardNum(pvc.getCardNum());
                InAccount inAccount = new InAccount("平安银行深圳分行营业部", pvc.getCardNum(), pinganOpen.getName(), "1.00");
                inAccounts.add(inAccount);
            }
            if(null != inAccounts && inAccounts.size()>0)
            {
                    String res = pingAnUtil.transferAccounts4018(type,inAccounts);
                    log.info(res);
                    jsonResult.setMessage(res);
            }
            else
            {
                jsonResult.setMessage("没有了");
            }
        }
        return new ResponseEntity<JsonResult>(jsonResult, HttpStatus.OK);
    }

    private String checkParam(String client, String callBack, String name, String idCard, String mobile, String code)
    {
        String message = null;
        //数据合法检查
        if (null == client || "null".equals(client.toLowerCase()) || StringUtils.isBlank(client))
        {
            message = "本次请求无效";
        }
        if (null == name || "null".equals(name.toLowerCase()) || StringUtils.isBlank(name))
        {
            message = "姓名不能为空";
        }

        if (null == idCard || "null".equals(idCard.toLowerCase()) || StringUtils.isBlank(idCard))
        {
            message = "身份证不能为空";
        }

        if (null == mobile || "null".equals(mobile.toLowerCase()) || StringUtils.isBlank(mobile))
        {
            message = "手机不能为空";
        }

        if (null == code || "null".equals(code.toLowerCase()) || StringUtils.isBlank(code))
        {
            message = "验证码不能为空";
        }
        return message;
    }

    private boolean checkVerifierCode(String mobile, String code)
    {
        //绕过验证码注册
        if (code.equalsIgnoreCase("dakaqiCode"))
        {
            return true;
        }
        //检查验证码是否正确
        String sessionId = redisClientTemplate.get(mobile);
        if (StringUtils.isBlank(sessionId))
            return false;
        else
        {
            try
            {
                return RongCloudSMS.verifyCode(sessionId, code);
            } catch (Exception e)
            {
                e.printStackTrace();
            }
        }
        return false;
    }
}
